const express = require('express');
const { WebSocketServer } = require('ws');
const http = require('http');

const app = express();
const server = http.createServer(app);

// 创建WebSocket服务并配置不同的路径
const wsPath1 = new WebSocketServer({ noServer: true });
const wsPath2 = new WebSocketServer({ noServer: true });

// 为不同路径的WebSocket服务设置连接事件
function setupConnection(ws, request, path) {
  // 从请求头中获取变量
  const someHeader = request.headers['your-header-name']; // 替换 'your-header-name' 为实际的请求头名称

  ws.on('message', function message(data) {
    console.log(`Received message on ${path}: ${data}`);
    const response = processMessage(data, path, someHeader);
    // 将处理后的消息（JSON格式）发送回客户端
    ws.send(JSON.stringify(response));
  });
}

wsPath1.on('connection', (ws, request) => setupConnection(ws, request, 'path1'));
wsPath2.on('connection', (ws, request) => setupConnection(ws, request, 'path2'));

// 处理WebSocket连接升级请求
server.on('upgrade', function upgrade(request, socket, head) {
  const { pathname } = new URL(request.url, `http://${request.headers.host}`);

  if (pathname === '/path1') {
    wsPath1.handleUpgrade(request, socket, head, ws => {
      wsPath1.emit('connection', ws, request);
    });
  } else if (pathname === '/path2') {
    wsPath2.handleUpgrade(request, socket, head, ws => {
      wsPath2.emit('connection', ws, request);
    });
  } else {
    socket.destroy();
  }
});

// 处理接收到的消息并返回一个响应
function processMessage(message, path, headerValue) {
  // 在这里添加你的消息处理逻辑
  return {
    path: path,
    receivedMessage: message,
    headerValue: headerValue,
    response: `Processed message (${message}) from ${path}`
  };
}

// 定义一个简单的路由
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// 服务器监听在3000端口
server.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});